package com.fejal.dao;


import java.util.List;
import com.fejal.bean.Professor;


public class ProfessorDAOHibernate implements ProfessorDAO {

	HibernateDAOFactory hibernateDAOFactory = null;
	HibernateDAO<Professor> hibernateDAO = null;

	public ProfessorDAOHibernate() {
		hibernateDAOFactory = new HibernateDAOFactory();
		hibernateDAO = hibernateDAOFactory.getProfessorDao();
	}

	@Override
	public boolean inserir(Professor professor) throws Exception {

		boolean ok = false;

		try {
			hibernateDAO.add(professor);
			ok = true;

		} catch (Exception e) {
			throw new Exception(e.getMessage());
		} 

		return ok;
	}

	@Override
	public boolean alterar(Professor professor) throws Exception{

		boolean ok = false;
	
		
		try {
			hibernateDAO.update(professor);
			ok = true;

		} catch (Exception e) {
			throw new Exception(e.getMessage());
		} 

		return ok;
	}

	@Override
	public boolean excluir(Professor professor) throws Exception{

		boolean ok = false;

		try {
			hibernateDAO.remove(professor);
			ok = true;

		} catch (Exception e) {
			throw new Exception(e.getMessage());
		} 

		return ok;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Professor> getSelecionar(String matricula, String CPF,  String nome) {
		
		String 	sql = "FROM com.fejal.bean.Professor as professor " + 
					  "WHERE codigoProfessor <> 0 ";
		
		if (!(matricula.isEmpty())) {
			sql += "AND matricula like '" + matricula + "%' ";  
		}

		if (!(CPF.isEmpty())) {
			sql += "AND pessoa.CPF like '" + CPF + "%' ";  
		}
		
		
		if (!(nome.isEmpty())) {
			sql += "AND pessoa.nome like '" + nome + "%' ";  
		}
		
		sql += "ORDER BY pessoa.nome";		
 
		List<Professor> lista = hibernateDAO.getSession().createQuery(sql).list();
		return lista;
	}

	@Override
	public Professor getProfessor(int codigoProfessor) {
		
		Professor professor = hibernateDAO.get(codigoProfessor);
		return professor;
	}

	@Override
	public List<Professor> getListTodos() {
		
		List<Professor> list = hibernateDAO.listAll();
		return list;
	}

	
	@SuppressWarnings("unchecked")
	@Override
	public boolean isExiste(Professor professor) {
		// SQL para verificar se a Professor existe
		String 	sql = 	"FROM Professor " +
				"WHERE codigoProfessor = "+professor.getCodigoProfessor();

		List<Professor> lista = hibernateDAO.getSession().createQuery(sql).list();
	    
		if(lista.size()<1){
			return false;
		} else {
			return true;
		}
	}

}
